import { getCookie, setCookie } from "@/utils/hsj";
const state = {
  componentsList: [],
  localList: JSON.parse(localStorage.getItem("localList") || "[]"),
  component: {},
  viewType: getCookie("viewType") || "drag",
};
let timer = null;
// 递归删除某一节点
function removeComponent(componentsList, component) {
  const index = componentsList.findIndex((item) => item.id === component.id);
  if (index === -1) {
    for (const item of componentsList) {
      const config = item["__config__"];
      if (config.children && config.children.length > 0) {
        removeComponent(config.children, component);
      }
    }
  } else {
    componentsList.splice(index, 1);
  }
}

const mutations = {
  // 加入component
  SET_COMPONENTS_LIST(state, component) {
    state.componentsList.push({ ...component });
  },
  // 更新componentlist
  UPDATE_COMPONENTS_LIST(state, componentsList) {
    state.componentsList = componentsList;
  },
  // 删除componentlist
  REMOVE_COMPONENTS_LIST(state, component) {
    if (component === "all") {
      state.component = "";
      state.componentsList = [];
    } else {
      removeComponent(state.componentsList, component);
    }
  },
  // 改变
  SET_COMPONENT(state, component) {
    if (!component.id) {
      component.id = new Date().getTime() + Math.random();
    }
    state.component = component;
    const index = state.componentsList.findIndex(
      (item) => item.id === state.component.id
    );
    if (index !== -1) {
      state.componentsList.splice(index, 1, state.component);
    }
  },
  // 保存本地htmlcompnent
  SAVE_HTMLCOMPONENT(state, component) {
    const str = new Date().getTime() + Math.random();
    const c = JSON.parse(JSON.stringify(component));
    c.id = str;
    c.__field__ = "field" + str;
    state.localList.push(c);
    localStorage.setItem("localList", JSON.stringify(state.localList));
  },
  // 删除本地htmlcomponent
  REMOVE_HTMLCOMPONENT(state, component) {
    const index = state.localList.findIndex((item) => item.id === component.id);
    if (index !== -1) {
      state.localList.splice(index, 1);
      localStorage.setItem("localList", JSON.stringify(state.localList));
    }
  },
  // 切换component
  CHANGE_COMPONENT(state, component) {
    state.component = component;
  },
  // 切换视图类型（自由拖拽，固定拖拽）
  CHANGE_VIEWTYPE(state) {
    state.viewType = state.viewType === "form" ? "drag" : "form";
    setCookie("viewType", state.viewType);
  },
};
const actions = {};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
